<template>
  <view class="container">
    <!-- 顶部套餐信息 -->
    <view class="top-panel">
      <view class="header">
        <u-icon name="arrow-left" size="40" color="#333" @click="goBack" class="back-button"></u-icon>
        <view class="title-box">
          <text class="package-title">{{ packageDetail.packageName || '普通入职体检' }}</text>
          <text class="package-category">{{ packageDetail.category || '入职体检' }}</text>
        </view>
      </view>
    </view>

    <!-- 医院信息 -->
    <view class="hospital-info">
      <text class="hospital-name">{{ hospitalName }}</text>
      <text class="hospital-address">{{ address }}</text>
    </view>

    <!-- 次日预约时间 -->
    <view class="time-section">
      <text class="section-title">次日预约时间</text>
      <view class="time-cards">
        <view
            class="time-card"
            :class="{ 'selected': selectedPeriod === 'am' }"
            @click="selectPeriod('am')"
        >
          <text class="period">上午</text>
          <text class="time-range">08:00-12:00</text>
          <text class="stock">剩余名额：{{ amStock }}</text>
        </view>
        <view
            class="time-card"
            :class="{ 'selected': selectedPeriod === 'pm' }"
            @click="selectPeriod('pm')"
        >
          <text class="period">下午</text>
          <text class="time-range">13:00-17:00</text>
          <text class="stock">剩余名额：{{ pmStock }}</text>
        </view>
      </view>
    </view>

    <!-- 底部购买栏 -->
    <view class="fixed-bottom">
      <view class="price-box">
        <text class="price-label">套餐价格</text>
        <text class="price">¥{{ packageDetail.price || '286' }}</text>
      </view>
      <button class="buy-btn" :disabled="!selectedPeriod" @click="handleBuy">去购买</button>
    </view>
  </view>
</template>

<script>
export default {
  data() {
    return {
      hospitalId: null,
      hospitalName: '北京市第二医院体检中心',
      address: '北京市西城区宣武门内大街潍坊胡同52号',
      packageDetail: {
        packageName: '普通入职体检',
        category: '入职体检',
        price: 286,
        id: null, // 从参数中获取
        validityPeriod: 30 // 假设从后端获取有效期，单位：天
      },
      amStock: 0, // 上午余量
      pmStock: 0, // 下午余量
      selectedPeriod: null // 选中的时间段（am/pm）
    };
  },
  onLoad(options) {
    // 从页面参数获取 packageId 和 hospitalId
    if (options.packageId) {
      this.packageDetail.id = options.packageId;
    }
    if (options.hospitalId) {
      this.hospitalId = options.hospitalId;
    }
    // 查询余量和套餐详情
    this.fetchStock();
    this.fetchPackageDetail();
  },
  methods: {
    // 查询余量
    fetchStock() {
      uni.showLoading({ title: '加载中...' });
      const tomorrow = this.getTomorrowDate();
      Promise.all([
        this.getStock(this.packageDetail.id, tomorrow, 'AM').then(stock => {
          this.amStock = stock;
        }).catch(() => {
          this.amStock = 0;
        }),
        this.getStock(this.packageDetail.id, tomorrow, 'PM').then(stock => {
          this.pmStock = stock;
        }).catch(() => {
          this.pmStock = 0;
        })
      ]).finally(() => {
        uni.hideLoading();
      });
    },
    // 获取次日日期（格式：yyyy-MM-dd）
    getTomorrowDate() {
      const today = new Date();
      const tomorrow = new Date(today);
      tomorrow.setDate(today.getDate() + 1);
      const year = tomorrow.getFullYear();
      const month = String(tomorrow.getMonth() + 1).padStart(2, '0');
      const day = String(tomorrow.getDate()).padStart(2, '0');
      return `${year}-${month}-${day}`;
    },
    // 查询余量方法
    getStock(physicalId, date, period) {
      return new Promise((resolve, reject) => {
        uni.request({
          url: 'http://localhost:8080/app/physical/inventory/remaining',
          method: 'GET',
          data: {
            physicalId: physicalId,
            date: date,
            period: period
          },
          success: (res) => {
            if (res.data.code === 200) {
              resolve(res.data.data); // 返回余量
            } else {
              uni.showToast({
                title: res.data.msg || '查询余量失败',
                icon: 'none'
              });
              reject();
            }
          },
          fail: (err) => {
            uni.showToast({
              title: '网络错误，请稍后重试',
              icon: 'none'
            });
            reject(err);
          }
        });
      });
    },
    // 查询套餐详情（包括有效期）
    fetchPackageDetail() {
      uni.request({
        url: `http://localhost:8080/app/physical/order/detail/${this.packageDetail.id}`,
        method: 'GET',
        success: (res) => {
          if (res.data.code === 200) {
            this.packageDetail = { ...this.packageDetail, ...res.data.data };
          } else {
            uni.showToast({
              title: res.data.msg || '查询套餐详情失败',
              icon: 'none'
            });
          }
        },
        fail: (err) => {
          uni.showToast({
            title: '网络错误，请稍后重试',
            icon: 'none'
          });
        }
      });
    },
    // 选择时间段
    selectPeriod(period) {
      this.selectedPeriod = period; // 记录选中的时间段（am/pm）
    },
    // 点击去购买
    handleBuy() {
      if (!this.selectedPeriod) {
        uni.showToast({
          title: '请选择预约时间段',
          icon: 'none'
        });
        return;
      }
      const tomorrow = this.getTomorrowDate();
      const period = this.selectedPeriod === 'am' ? 'AM' : 'PM';
      uni.navigateTo({
        url: `/pages/physical/order?packageId=${this.packageDetail.id}&hospitalId=${this.hospitalId}&date=${tomorrow}&period=${period}`
      });
    },
    goBack() {
      uni.navigateBack();
    }
  }
};
</script>

<style>
.container {
  padding-bottom: 120rpx;
}

/* 顶部套餐信息 */
.header {
  display: flex;
  align-items: center;
  padding: 20rpx;
}

.title-box {
  margin-left: 80rpx;
}

.package-title {
  font-size: 36rpx;
  font-weight: bold;
  display: block;
}

.package-category {
  font-size: 28rpx;
  color: #666;
}

/* 医院信息 */
.hospital-info {
  padding: 30rpx;
  background: #fff;
  border-bottom: 1rpx solid #eee;
}

.hospital-name {
  font-size: 32rpx;
  display: block;
  margin-bottom: 10rpx;
}

.hospital-address {
  font-size: 28rpx;
  color: #666;
}

/* 预约时间 */
.time-section {
  padding: 30rpx;
}

.section-title {
  font-size: 32rpx;
  font-weight: bold;
  display: block;
  margin-bottom: 20rpx;
}

.time-cards {
  display: flex;
  gap: 20rpx;
}

.time-card {
  flex: 1;
  padding: 20rpx;
  border: 1rpx solid #007AFF;
  border-radius: 12rpx;
  background: #fff;
}

.time-card.selected {
  background: #e6f0ff; /* 高亮背景色 */
  border-color: #0055ff; /* 高亮边框色 */
}

.period {
  font-size: 28rpx;
  color: #007AFF;
  display: block;
}

.time-range {
  font-size: 24rpx;
  color: #666;
  margin: 10rpx 0;
}

.stock {
  font-size: 24rpx;
  color: #FF4444;
  margin-bottom: 10rpx;
  display: block;
}

/* 底部购买栏 */
.fixed-bottom {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  height: 100rpx;
  background: white;
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20rpx;
  box-shadow: 0 -2rpx 10rpx rgba(0, 0, 0, 0.1);
}

.price-box {
  display: flex;
  align-items: baseline;
}

.price-label {
  font-size: 28rpx;
  color: #666;
  margin-right: 10rpx;
}

.price {
  font-size: 36rpx;
  color: #FF4444;
  font-weight: bold;
}

.buy-btn {
  background: #007AFF;
  color: white;
  font-size: 32rpx;
  padding: 0 60rpx;
  border-radius: 50rpx;
  line-height: 2.2;
}

.buy-btn[disabled] {
  background: #cccccc;
  color: #999999;
}
</style>